package com.yami.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.dto.FriendSaveDTO;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.event.SendPersonMessageEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.NotifyTemplateParam;
import com.yami.shop.bean.vo.MyFriendVo;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.dao.FriendMapper;
import com.yami.shop.dao.UserBlockMapper;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.service.FriendService;
import com.yami.shop.service.MeltCloudGroupUserService;
import com.yami.shop.service.MeltCloudUserRemarkService;
import com.yami.shop.service.UserSecurityConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class FriendServiceImpl extends ServiceImpl<FriendMapper, Friend> implements FriendService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserSecurityConfigService userSecurityConfigService;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private MeltCloudGroupUserService meltCloudGroupUserService;
    @Autowired
    private UserBlockMapper userBlockMapper;
    @Autowired
    private MeltCloudUserRemarkService userRemarkService;
    /**
     * 关注指定人
     *
     * @param saveDTO
     */
    @Override
    public void follow(FriendSaveDTO saveDTO) {
        // 取消关注
        if (StrUtil.equals("1", saveDTO.getType())) {
            LambdaQueryWrapper<Friend> eq = new LambdaQueryWrapper<Friend>()
                    .eq(Friend::getUserId, saveDTO.getUserId())
                    .eq(Friend::getFriendId, saveDTO.getFriendId());
            this.remove(eq);
        } else {
            LambdaQueryWrapper<Friend> eq = new LambdaQueryWrapper<Friend>()
                    .eq(Friend::getUserId, saveDTO.getUserId())
                    .eq(Friend::getDelFlag, 0)
                    .eq(Friend::getFriendId, saveDTO.getFriendId());
            List<Friend> friends = baseMapper.selectList(eq);
            if(ObjectUtil.isNull(friends)||friends.size()==0){
                UserBlock one = userBlockMapper.selectOne(Wrappers.lambdaQuery(UserBlock.class).eq(UserBlock::getUserId, saveDTO.getFriendId()).eq(UserBlock::getBlockUserId, saveDTO.getUserId()));
                if (Objects.nonNull(one)) {
                    throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "根据对方设置，您不能进行此操作");
                }
                UserBlock one1 = userBlockMapper.selectOne(Wrappers.lambdaQuery(UserBlock.class).eq(UserBlock::getUserId, saveDTO.getUserId()).eq(UserBlock::getBlockUserId, saveDTO.getFriendId()));
                if (Objects.nonNull(one1)) {
                    throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "您已拉黑对方，请取消拉黑");
                }
                // 关注
                Friend friend = BeanUtil.copyProperties(saveDTO, Friend.class, "type");
                this.save(friend);
                //关注消息
                NotifyTemplateParam shopParam = new NotifyTemplateParam();
                shopParam.setShopId(Constant.PLATFORM_SHOP_ID);
                shopParam.setSendType(SendType.FOLLOW_REMINDER.getValue());
                shopParam.setUserId(saveDTO.getFriendId());
                shopParam.setFromUserId(saveDTO.getUserId());
                shopParam.setType(4);
                applicationContext.publishEvent(new SendPersonMessageEvent(shopParam));
            }
        }
    }

    /**
     * 我的关注列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<MyFriendVo> firendList(String userId, String userName) {
        return baseMapper.firendList(userId, userName);
    }

    /**
     * 新增关注列表
     *
     * @param userID
     * @return
     */
    @Override
    public List<MyFriendVo> newConcernsList(String userID) {
        return baseMapper.newConcernsList(userID);
    }

    @Override
    public Map<String, Object> selectFansFollowNum(String usId) {
        return baseMapper.selectFansFollowNum(usId);
    }

    @Override
    public int getRelation(String usId, String current) {
        return baseMapper.getRelation(usId,current);
    }

    @Override
    public Map<String, Object> gethome(String usId, String currentId) {
        String infoId = StrUtil.isEmpty(usId)?currentId:usId;
        //获取主页信息
        User userDetail = userMapper.getUserDetail(infoId);
        if(ObjectUtil.isNull(userDetail)){
            throw new YamiShopBindException("yami.sys.illegalArgument");
        }
        Map<String, Object> stringObjectMap = baseMapper.selectFansFollowNum(infoId);
        Integer myFriendCount = baseMapper.myFriendListPageCount(infoId);
        String real = "0";
        if(ObjectUtils.isEmpty(userDetail.getIdNumber())){
            real = "0";  //未实名
        }else{
            real = "1";  //已实名
        }
        stringObjectMap.put("myFriendCount",myFriendCount);
        stringObjectMap.put("nickName",userDetail.getNickName());
        stringObjectMap.put("pic",userDetail.getPic());
        stringObjectMap.put("real",real);
        //1女2男
        if(StrUtil.isNotEmpty(userDetail.getIdNumber()) && StrUtil.isEmpty(userDetail.getSex())){
            stringObjectMap.put("sex",IdcardUtil.isValidCard(userDetail.getIdNumber())? IdcardUtil.getGenderByIdCard(userDetail.getIdNumber())==1?"M":"F" :null);
        }else{
            stringObjectMap.put("sex",userDetail.getSex());
        }
        stringObjectMap.put("age",StrUtil.isNotEmpty(userDetail.getIdNumber())&&IdcardUtil.isValidCard(userDetail.getIdNumber())?IdcardUtil.getAgeByIdCard(userDetail.getIdNumber()):null);
        stringObjectMap.put("ip",userDetail.getUserRegip());
        stringObjectMap.put("moodState",userDetail.getMoodState());
        stringObjectMap.put("relation",null);
        stringObjectMap.put("massageSwitch",null);
        stringObjectMap.put("followSwitch",null);
        stringObjectMap.put("fanSwitch",null);
        stringObjectMap.put("remark",null);
        //获取省份
        log.info("获取省份");
        stringObjectMap.put("province",IPHelper.getIpProvinceAddr(userDetail.getUserRegip()));
        //如果是访友主页 获取访友的隐私配置
        if(StrUtil.isNotEmpty(usId)){
            //0: 陌生人 1：粉丝 2：已关注 3：互相关注
            int relation = baseMapper.getRelation(usId, currentId);
            stringObjectMap.put("relation",relation);
            UserSecurityConfig userSecurityConfig = userSecurityConfigService.getOne(new LambdaQueryWrapper<UserSecurityConfig>().eq(UserSecurityConfig::getUserId, usId));
            String massageSwitch = "on";
            String followSwitch = "on";
            String fanSwitch = "on";
            if(ObjectUtil.isNotNull(userSecurityConfig)){
                //谁可私信我：0默认1我关注的人2互相关注的人3禁止私信
                String privacyType = userSecurityConfig.getPrivacyType();
                massageSwitch = getPrivacyTypeValue(relation,privacyType);
                String privacyFan = userSecurityConfig.getPrivacyFan();
                fanSwitch = "0".equals(privacyFan)?"on":"off";
                String privacyFollow = userSecurityConfig.getPrivacyFollow();
                followSwitch = "0".equals(privacyFollow)?"on":"off";
            }
            stringObjectMap.put("massageSwitch",massageSwitch);
            stringObjectMap.put("followSwitch",followSwitch);
            stringObjectMap.put("fanSwitch",fanSwitch);
            MeltCloudUserRemark one = userRemarkService.getOne(Wrappers.lambdaQuery(MeltCloudUserRemark.class)
                    .eq(MeltCloudUserRemark::getUserId, currentId).eq(MeltCloudUserRemark::getType, 1).eq(MeltCloudUserRemark::getObjId, usId));
            if (one != null && StringUtils.isNotEmpty(one.getRemark()))
                stringObjectMap.put("remark", one.getRemark());
        }
        return stringObjectMap;
    }
    @Override
    public String getPrivacyTypeValue(Integer relation, String privacyType) {
        String massageSwitch = "on";
        //0: 陌生人 1：粉丝 2：已关注 3：互相关注
            //谁可私信我：0默认1我关注的人2互相关注的人3禁止私信
        switch (privacyType){
            case "3": massageSwitch = "off"; break;
            case "2": massageSwitch = relation==3?  "on":"off"; break;
            case "1": massageSwitch = relation==1 || relation==3?  "on":"off"; break;
            case "0": massageSwitch = "on"; break;
            default:massageSwitch = "off";break;
        }
        return massageSwitch;
    }

    @Override
    public List<MyFriendVo> getRelations(List<String> userIds, String current) {
        return baseMapper.getRelations(userIds,current);
    }

    @Override
    public void removeEachOtherFan(String userId, String usId) {
        LambdaQueryWrapper<Friend> weq = new LambdaQueryWrapper<Friend>()
                .eq(Friend::getUserId, userId)
                .eq(Friend::getFriendId, usId);
        this.remove(weq);
        LambdaQueryWrapper<Friend> eq = new LambdaQueryWrapper<Friend>()
                .eq(Friend::getUserId, usId)
                .eq(Friend::getFriendId, userId);
        this.remove(eq);
    }


    @Override
    public IPage<MyFriendVo> fansPage(Page page ,String usId, String currentId) {
        String infoId = StrUtil.isEmpty(usId)?currentId:usId;
        return baseMapper.fansPage(page,infoId,currentId);
    }

    @Override
    public IPage<MyFriendVo> fansPageSearch(Page page, String currentId, String userName, String groupId) {
        IPage<MyFriendVo> myFriendVoIPage = baseMapper.fansPageSearch(page, currentId, userName);
        if(ObjectUtil.isNotEmpty(groupId)){
            for(MyFriendVo myFriendVo:myFriendVoIPage.getRecords()){
                MeltCloudGroupUser one = meltCloudGroupUserService.getOne(new LambdaQueryWrapper<MeltCloudGroupUser>().eq(MeltCloudGroupUser::getGroupId, Long.valueOf(groupId)).eq(MeltCloudGroupUser::getUserId, myFriendVo.getId()));
                if(ObjectUtil.isNotEmpty(one)){
                    if("0".equals(one.getIsDel())){
                        myFriendVo.setGroupStatus("0");
                    }else{
                        myFriendVo.setGroupStatus("1");
                    }
                }else{
                    //0存在 1不存在
                    myFriendVo.setGroupStatus("1");
                }
            }
        }
        return myFriendVoIPage;
    }

    @Override
    public IPage<MyFriendVo> followPage(Page page,String usId, String currentId) {
        String infoId = StrUtil.isEmpty(usId)?currentId:usId;
        return baseMapper.followPage(page,infoId,currentId);
    }

    @Override
    public IPage<MyFriendVo> myFriendListPage(Page page, String usId ,String currentId,String userName) {
        String infoId = StrUtil.isEmpty(usId)?currentId:usId;
        return baseMapper.myFriendListPage(page,infoId,currentId,userName);
    }

    @Override
    public IPage<MyFriendVo> searchUserListPage(Page page, String currentId, String userName) {
        return baseMapper.searchUserListPage(page,currentId,userName);
    }

    @Override
    public List<MyFriendVo> followPageNoPage(String currentId) {
        return baseMapper.followPageNoPage(currentId);
    }

    @Override
    public IPage<MyFriendVo> recommendList(Page page,String userName, String currentId) {
        return baseMapper.recommendList(page,userName,currentId);
    }

    @Override
    public void followRecommend(List<MyFriendVo> records,String currentId) {
        // 批量关注
        List<Friend> list = new ArrayList<>();
        for (MyFriendVo myFriendVo:records) {
            Friend friend = new Friend();
            friend.setFriendId(myFriendVo.getId());
            friend.setUserId(currentId);
            list.add(friend);
        }
        this.saveBatch(list);
    }

    @Override
    public void removeAllFirend(String userId) {
         baseMapper.removeAllFirend(userId);
    }
}
